<!--新页面模板-->
<template>
  <!--  风险点调查记录-->
  <div class="box-view">
    <el-row :gutter="15">
      <el-col :span="4" class="left_org">
        <!-- 搜索框 -->
        <organization-tree v-model="deptTree" ref="deptTree" :changeOnSelect='true' placeholder="选择管养单位"
                           @change="selectOrgHandel"></organization-tree>
      </el-col>
      <el-col :span="20">
        <div class="page">
          <div style="padding: 20px 0px 0px 20px">
            <el-breadcrumb separator-class="el-icon-arrow-right">
              <el-breadcrumb-item @click.native="breadClick(item.deptTreeIdList)" v-for="item in deptTree.breadList"
                                  :key="item.name">
                <el-button type="text" class="bread_button_text">{{item.deptName}}</el-button>
              </el-breadcrumb-item>
            </el-breadcrumb>
          </div>
          <el-divider></el-divider>
          <!-- 条件筛选 -->
          <div class="page_filter">
            <el-input v-model="form.queryString" clearable placeholder="请输入灾害名称或编号">
              <template slot="prepend">灾害名称/编号</template>
            </el-input>
            <el-autocomplete
              v-model="state"
              clearable
              :fetch-suggestions="querySearchAsync"
              placeholder="请输入路线名称或编号"
              @change="handleChange"
              @select="handleSelect"
            ></el-autocomplete>
<!--            <el-select v-model="form.roadId" filterable clearable placeholder="选择路线">-->
<!--              <el-option-->
<!--                v-for="item in deptRoadList"-->
<!--                :key="item.id"-->
<!--                :label="item.name"-->
<!--                :value="item.id">-->
<!--              </el-option>-->
<!--            </el-select>-->
            <el-select v-model="form.damageType" clearable placeholder="灾害类型" @change="changeDamageType">
              <el-option
                v-for="item in EnumDamageTypeList"
                :key="item.code"
                :label="item.name"
                :value="item.code">
              </el-option>
            </el-select>
            <el-select v-model="form.damageId" filterable clearable placeholder="选择灾害点(先选择类型)"
                       @focus="getDamagePointList">
              <el-option
                v-for="item in damageSelectList"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
            <el-select v-model="form.riskLevel" filterable clearable placeholder="选择评估等级">
              <el-option
                v-for="item in EnumDamageRiskList"
                :key="item.code"
                :label="item.name"
                :value="item.code">
              </el-option>
            </el-select>
            <el-button class="common_btn-defalut" icon="el-icon-search" @click="form.page=1;queryList()">搜索</el-button>
          </div>
          <div class="page_main">
            <el-button class=" common_btn-defalut" style="margin-bottom: 20px" @click="add" :disabled="hasPermission('damage:risk:add')?false:'disabled'">填写风险点调查表</el-button>
            <el-radio-group v-model="form.isQueryHistory" @change="form.page=1;queryList()">
              <el-radio-button v-for="item in EnumSysBooleanList" :key="item.code" :label="item.code">{{item.name}}
              </el-radio-button>
            </el-radio-group>
            <div class="common_btnBox">
              <i class="iconfont iconzongshu icon-size"></i>
              总数：{{form.total}}
            </div>
            <el-table :data="tableList" border>
              <el-table-column label="序号" width="70">
                <template slot-scope="scope">
                  {{getIndex(scope.$index)}}
                </template>
              </el-table-column>
              <el-table-column prop="roadCode" width="100" label="路线编号"></el-table-column>
              <el-table-column prop="roadName" show-overflow-tooltip width="120" label="路线名称"></el-table-column>
              <el-table-column prop="deptName" show-overflow-tooltip width="150" label="管养单位"></el-table-column>
              <el-table-column prop="damageNo" show-overflow-tooltip min-width="160" label="灾害点编号"></el-table-column>
              <el-table-column prop="name" show-overflow-tooltip min-width="120" label="灾害点名称"></el-table-column>
              <el-table-column prop="damageTypeName" min-width="120" label="灾害类型"></el-table-column>
              <!--              <el-table-column prop="unitName" min-width="120" show-overflow-tooltip label="排查单位"></el-table-column>-->
              <el-table-column prop="userName" min-width="100" show-overflow-tooltip label="排查人"></el-table-column>
              <el-table-column min-width="140" show-overflow-tooltip label="风险指数">
                <el-table-column prop="riskLevelName" min-width="120" label="评估等级">
                  <template slot-scope="scope">
                    <p>{{scope.row.cri}}</p>
                    <el-tag size="mini" :style="scope.row.riskLevel| gradeDangerColor"
                            style="color: white">
                      {{scope.row.riskLevelName}}
                    </el-tag>
                  </template>
                </el-table-column>
                <template slot-scope="scope">
                  <p>【{{scope.row.riskLevelName}}】</p>
                </template>
              </el-table-column>
              <el-table-column prop="investigateTime" width="165" label="排查时间">
                <template slot-scope="scope">{{scope.row.createTime | formatTimer}}</template>
              </el-table-column>
              <el-table-column prop="count" width="100" sortable label="次序"></el-table-column>
              <el-table-column label="操作" fixed="right" width="180">
                <template slot-scope="scope">
                  <button class="btn_edit" @click="chekDeatil(scope.row)">查看详情</button>
                  <button class="btn_add" @click="editDetail(scope.row)" v-if="hasPermission('damage:risk:add')&&form.isQueryHistory==0">编辑</button>
                  <el-popconfirm v-if="hasPermission('damage:risk:del')" confirmButtonText='好的' cancelButtonText='不用了' icon="" title="确定删除吗？" @confirm="handleDelete(scope.row.id)">
                    <button slot="reference" class="btn_delete">删除</button>
                  </el-popconfirm>
                </template>
              </el-table-column>
            </el-table>
            <!-- 分页器 -->
            <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="form.page"
              :page-size="form.pageSize"
                 :page-sizes="[10, 20, 30, 40,50,60,70,80,90,100]"
              layout="sizes, prev, pager, next"
              :total="form.total">
            </el-pagination>
          </div>
          <!--查看、编辑-->
          <el-drawer :key="drawerDetailKey" :title="showDetailTitle"
                     :visible.sync="detailDrawer"
                     custom-class="demo-drawer" size="50%">
            <div class="demo-drawer__content">
              <Damage-risk-form-detail ref="operation" :currentRow="currentRow" :template="currentRow.formList" :isLook="isLook"
                             @submit="submit"></Damage-risk-form-detail>
            </div>
            <!--新增-->
          </el-drawer>
          <el-drawer

            title="风险点调查表"
            :visible.sync="newForm"
            direction="ltr"
            :key="drawerKey"
            custom-class="demo-drawer"
            ref="drawer"
            size="70%">
            <div class="demo-drawer__content">
              <damage-risk-form ref="damageForm" @submitClose="submitClose" @disableds="disableds"></damage-risk-form>
            </div>
            <div class="demo-drawer__footer">
              <el-button @click="newForm=false" type="info">取 消</el-button>
              <el-button type="primary"  :disabled="isDisabled" class=" common_btn-defalut" @click="submitDrawer">确 定</el-button>
            </div>
          </el-drawer>
          <!-- 查看大图 -->
          <picture-viewer ref="imageViewer"></picture-viewer>
        </div>
      </el-col>
    </el-row>
    <x-loading v-show="isLoading"></x-loading>
  </div>
</template>
<script>
import DamageRiskForm from "./damageRiskForm";
import ItemMixins from "../item.mixins";
import OrganizationTree from '@/components/organization-tree/all'
import PictureViewer from '@/components/picture-viewer/index-name'
import constUrl from '@/services/env'
import {getDamageFormList, getDamageDetail,damageDelete} from '@/services/model/form';
import DamageRiskFormDetail from "./modules/damage-risk-form-detail";
import Enums from '@/utils/enums'
import XLoading from '@/components/animation/x-loading.vue'

export default {
  components: {
    DamageRiskForm,
    PictureViewer,
    DamageRiskFormDetail,
    OrganizationTree,
    XLoading
  },
  mixins: [ItemMixins,Enums],
  data() {
    return {
      isLoading: false,
      restaurants:[],
      state: '',
      timeout:  null,
      isDisabled:false,
      drawerKey: 1,
      drawerDetailKey: 100,
      newForm: false,
      showDetailTitle: '',
      deptTree: {
        breadList: [],//面包屑
        deptTreeId: '',
      },
      constUrl,
      tableList: [],
      EnumSysBooleanList: [
        {code: 0, name: '最新一次'},
        {code: 1, name: '历史所有'},

      ],
      deptRoadList: [],
      damageList: [],
      currentRow: {},
      EnumDamageTypeList: [],
      EnumDamageRiskList: [],
      form: {
        page: 1,
        pageSize: 10,
        roadSectionId: '',
        isQueryHistory: 0,
      },
      detailDrawer: false,
      isLook: true,
    }
  },
  watch: {},
  computed: {},
  methods: {
    async handleDelete(id){
      let res = await damageDelete({id:id})
      if (res.code === 200) {
        this.$notify({
          type: 'success',
          title: '提示',
          message: '删除成功'
        })
      }
      this.queryList()
    },
    getDamagePointList() {
      if (!this.form.roadId) {
        this.$message('请先选择路线');
        return
      }
      if (!this.form.damageType) {
        this.$message('请先选择灾害类型');
      }
    },
    add() {
      this.newForm = true
this.$nextTick(()=>{
  this.$refs.damageForm.headAdd()
})
      this.isDisabled=false
    },
    disableds(value){
      this.isDisabled=value
    },
    submitClose() {
      this.drawerKey += 1
      this.newForm = false
      this.queryList()
    },
    submitDrawer() {
      this.$refs.damageForm.validatorForm()


    },
    submit() {
      this.currentRow = {};
      this.detailDrawer = false
      this.drawerDetailKey += 1
      this.queryList()
    },
    //面包屑跳转
    breadClick(deptTreeId) {
      this.$refs.deptTree.changeBread(deptTreeId)
    },
    //组织机构组件回调
    selectOrgHandel() {
      this.$forceUpdate()
      this.$set(this.form, 'roadId', '');
      this.$set(this.form, 'damageType', '');
      this.$set(this.form, 'damageId', '');
      this.form.deptTreeId = this.deptTree.deptTreeId
      this.queryList()
      this.changeDept()
    },
    async chekDeatil(row) {
      this.showDetailTitle = '风险点调查记录详情'
      this.detailDrawer = true
      this.isLook = true
      let detail = await getDamageDetail({id: row.id})
      detail.data.riskLevel=row.riskLevel
      detail.data.riskLevelName=row.riskLevelName
      this.currentRow = detail.data
    },
    async editDetail(row) {
      this.showDetailTitle = '编辑风险点调查记录'
      this.detailDrawer = true
      this.isLook = false
      let detail = await getDamageDetail({id: row.id})
      detail.data.riskLevel=row.riskLevel
      detail.data.riskLevelName=row.riskLevelName
      this.currentRow = detail.data
      this.$nextTick(function () {
        this.$refs.operation.changeDept();
      });
    },
    // 查看大图
    previewImg(index, urls) {
      const urlList = JSON.parse(JSON.stringify(urls))
      urlList.map(x => {
        x.url = this.constUrl + x.url
        return x
      })
      this.$refs.imageViewer.showViewer(urlList, index)
    },
    // 获取当前的序号
    getIndex(index) {
      let param = (this.form.page - 1) * this.form.pageSize + index + 1
      return param
    },
    async queryList() {
      this.isLoading = true
      let res = await getDamageFormList(this.form)
      this.tableList = res.data?.records || []
      this.form.page = Number(res.data?.current)
      this.form.total = Number(res.data?.total)
      this.isLoading = false
    },
    // 分页大小改变
    handleSizeChange(val) {
      this.form.pageSize = val
      this.queryList()
    },
    // 当前页码改变
    handleCurrentChange(val) {
      this.form.page = val
      this.queryList()
    },
    changeDamageType() {
      this.$set(this.form, 'damageId', '');
      this.damageSelectList = []
      const {deptTreeId, roadId, damageType} = this.form
      this.getDamageSelectList(deptTreeId, roadId, damageType)
    },
    // 模糊搜索路线
    querySearchAsync(queryString, cb) {
      var restaurants
      if(!queryString){
        restaurants = [];
      }else {
        restaurants = this.restaurants;

      }
      var results = queryString ? restaurants.filter(this.createStateFilter(queryString)) : restaurants;
      clearTimeout(this.timeout);
      this.timeout = setTimeout(() => {
        cb(results);
      }, 10 * Math.random());
    },
    createStateFilter(queryString) {
      return (state) => {
        return (state.value.toLowerCase().indexOf(queryString.toLowerCase()) >-1);
      };
    },
    handleSelect(item) {
      this.form.roadId=item.id
      this.changeRoad()
    },
    //获取路线列表
    async changeDept() {
      this.deptRoadList = await this.getRoadListByDept(this.form.deptTreeId)
      let data=[]
      this.deptRoadList.map(x=>{
        data.push({
          id:x.id,
          value:x.name,
          name:x.name
        })
      })
      this.restaurants=data
    },
  },
  mounted() {
    // // 查询单位类型
    this.queryDictList(['EnumDamageType','EnumDamageRiskLevel'],
      ['EnumDamageTypeList','EnumDamageRiskList']);
  },
  activated() {

  },
}


</script>
<style scoped="scoped" lang="less">
  .box-view {
    .left_org {
      height: calc(100% - 83px);
      border-radius: 8px;
    }

    .page {
      .page_filter {
        padding: 0px 20px;
      }
    }
  }

  .bread_button_text {
    padding-right: 0px;
    font-size: 18px;
    font-weight: 600;
    color: #1990FE;
  }

  /deep/ .demo-drawer {

    .demo-drawer__content {
      width: 100%;
      height: 90%;
    }

    .demo-drawer__footer {
      bottom: 5%;
    }
  }
</style>
